#include "topsail.h"
#include "error.h"

int Socket(int domain, int type, int protocol, char *file, int line)
{
	if ( -1 == socket(domain, type, protocol)) 
		err_sys(file, line, "socket error");
	return 0;
}

int Bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen, char *file, int line)
{
	if ( -1 == bind(sockfd, my_addr, addrlen))
		err_sys(file, line, "bind error");
	return 0;
}

int Listen(int sockfd, int backlog, char *file, int line)
{
	if ( -1 == listen(sockfd, backlog))
		err_sys(file, line, "listen error");
	return 0;
}

int Accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen, char *file, int line)
{
	if ( -1 == accept(sockfd, addr, addrlen))
		err_sys(file, line, "accept error");
	return 0;
}

pid_t Fork(char *file, int line)
{
	if ( -1 == fork())
		err_sys(file, line, "fork error");
	return 0;
}

int Close(int fd, char *file, int line)
{
	if ( -1 == close(fd))
		err_sys(file, line, "close error");
	return 0;
}

FILE *Fdopen(int fd, const char *mode, char *file, int line)
{
	FILE *fp;
	if ( NULL == (fp = fdopen(fd, mode)))
		err_sys(file, line, "fdopen error");
	return fp;
}

int Chdir(const char *path, char *file, int line)
{
	if ( -1 == chdir(path))
		err_sys(file, line, "chdir error");
	return 0;
}

int Lstat(const char *path, struct stat *buf, char *file, int line)
{
	if ( -1 == lstat(path, buf))
		err_sys(file, line, "lstat error");
	return 0;
}

DIR *Opendir(const char *name, char *file, int line)
{
	DIR *dp;
	if ( NULL == (dp = opendir(name)))
		err_sys(file, line, "opendir error");
	return dp;
}

int Closedir(DIR *dir, char *file, int line)
{
	if ( -1 == closedir(dir))
		err_sys(file, line, "closedir error");
	return 0;
}

FILE *Fopen(const char *path, const char *mode, char *file, int line)
{
	FILE *fp;
	if ( NULL == (fp = fopen(path, mode))) 
		err_sys(file, line, "fopen error!");
	
	return fp;
}

int Fclose(FILE *fp, char *file, int line)
{
	if ( EOF == fclose(fp)) 
		err_sys(file, line, "fclose error");
	return 0;
}

int Open(const char *pathname, int flags, char *file, int line)
{
	int fd;
	if ( -1 == (fd = open(pathname, flags)))
		err_sys(file, line, "open error");
	return fd;
}

void *Malloc(size_t size, char *file, int line)
{
	void *p;
	if ( NULL == (p = malloc(size)))
		err_sys(file, line, "malloc error");
	return p;
}

int Rename(const char *oldpath, const char *newpath, char *file, int line)
{
	if ( -1 == rename(oldpath, newpath))
		err_sys(file, line, "rename error");
	return 0;
}

